package com.yiwei.controller.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * @Description 图片分隔-发微信朋友圈
 * @Author cheng2839
 * @Date 2018年10月04日
 * @Version v1.0
 */
public class ImgSpliterUtils {

	public static void main(String[] args) {
		try {
			String IMAGE_FILE_PATH = "D:\\report.jpg";
			int x = 1;
			int y = 6;
			sepImage(IMAGE_FILE_PATH, x, y);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void sepImage(String IMAGE_FILE_PATH, int SEP_X_NUM, int SEP_Y_NUM) throws IOException {
		File file = new File(IMAGE_FILE_PATH);
		if (!file.exists() || !file.isFile()) {
			throw new RuntimeException("file not exists or un-file:" + IMAGE_FILE_PATH);
		}
		BufferedImage image = ImageIO.read(file);
		int totalWidth = image.getWidth();
		int totalHeight = image.getHeight();
		int width = totalWidth / (SEP_X_NUM <= 0 ? 1 : SEP_X_NUM);
		int height = totalHeight / (SEP_Y_NUM <= 0 ? 1 : SEP_Y_NUM);

		File dirFile = new File(file.getParent(), file.getName().substring(0, file.getName().lastIndexOf(".")));
		if (!dirFile.exists()) {
			dirFile.mkdir();
		}

		for (int y = 0, j = 1; y <= totalHeight - height; y += height, j++) {
			for (int x = 0, i = 1; x <= totalWidth - width; x += width, i++) {
				File targetFile = new File(dirFile, j + "_" + i + ".jpg");
				BufferedImage targetImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
				Graphics g = targetImage.getGraphics();
				System.out.println(targetFile.getPath() + ":    x=" + x + ",y=" + y + "; width=" + width + ", height="
						+ height + "; totalWidth" + totalWidth + ",totalHeight=" + totalHeight);
				g.drawImage(image.getSubimage(x, y, width, height), 0, 0, null);
				ImageIO.write(targetImage, "JPG", targetFile);
			}
		}
	}

}